const express = require('express');
const router = express.Router();
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const co = require('co');

const DB = require('../db');
const DT = require('../lib/dt');
const EJS = require('../lib/ejs');

router.get('/', function (req, res, next) {
    co(function* () {
        const yue = req.query.yue || DT.today.nongM;
        const data = yield DB.Person.findAll({
            raw: true,
            where: {
                nong: {
                    [Op.substring]: '-' + DT.repair(yue) + '-',
                },
            },
            order: [
                Sequelize.fn('substr', Sequelize.col('nong'), 6),
            ],
        });
        res.render('wall', {yue: yue, data: data});
    }).catch((err) => {
        next(err)
    })
});

router.get('/next/:nong', function (req, res, next) {
    co(function* () {
        const todayId = DT.today.id;
        const nong = req.params.nong;
        const arr = nong.split('-');
        const data = yield DB.Calendar.findOne({
            raw: true,
            where: {
                id: {
                    [Op.gt]: todayId,
                },
                nong: {
                    [Op.like]: `%-${parseInt(arr[1])}-${parseInt(arr[2])}`,
                }
            },
        });
        const hasDay = data.id - todayId;
        res.end(hasDay.toString());
    }).catch((err) => {
        next(err)
    })
});

module.exports = router;
